﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace CollectionFactories
{
    using System;
    using System.IO;
    using PivotServerTools;
    using Microsoft.Office.Server.Search;
    using Microsoft.Office.Server.Search.Query;
    using Microsoft.Office.Server.Search.Administration;


    /**
     * Collection of SharePoint people search results
     */
    public class SPPeopleSearch : CollectionFactoryBase
    {
        
        private const string RES_NAME_COLUMNS =   "CollectionFactories.Resource.RequestedProperties.xml";
        private const string RES_NAME_TRANSFORM = "CollectionFactories.Resource.SearchResults.xsl";

        public const string CollectionName = "PeopleSearch";
        private const string DefaultDocumentLocation = @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\o14_person_placeholder_96.png";
        public const string DefaultQuery = "southridge";

        public SPPeopleSearch()
        {
            this.Name = CollectionName;
            this.Summary = "A collection of F4SP people search results on this server.";
        }

        public override Collection MakeCollection(CollectionRequestContext context)
        {
            return MakeCollection(this.Name);
        }

        /**
         * Make a query and get rresults from People Search
         */
        public Collection MakeCollection(string collectionFileName)
        {

             SearchServiceApplicationProxy searchProxy =
            (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(
                                            SPServiceContext.GetContext(SPContext.Current.Site));
               
                LocationList locationList = new LocationList();
                QueryManager queryManager = new QueryManager();
                
                Location localSearchLocation = new Location("LocalPeopleSearchIndex", searchProxy);
                localSearchLocation.TrimExtraProperties = false;
                localSearchLocation.AllowMissingProperties = true;

                localSearchLocation.EnableStemming = true;
                localSearchLocation.EnablePhonetic = true;
                localSearchLocation.EnableNicknames = true;
                localSearchLocation.CurrentUserProfile = Microsoft.Office.Server.UserProfiles.ProfileLoader.GetProfileLoader().GetUserProfile();
                localSearchLocation.RankingModelID = "0BBA4D7D-4F2C-4086-975A-8F9D2B6C6D53";
                localSearchLocation.ItemsPerPage = SPPivotSettings.MaxItems == null ? 1000 : (int)SPPivotSettings.MaxItems;

                // add our managed properties                    
                    XDocument xDocProps = XDocument.Parse(SPPivotSettings.FacetCategories);
                    IEnumerable<string> list1 = from el in xDocProps.Root.Elements("Column")
                                                select el.Attribute("Name").Value;
                    StringCollection Properties = new StringCollection();
                    Properties.AddRange(list1.ToArray<string>());
                    localSearchLocation.RequestedProperties = Properties;              
                

                locationList.Add(localSearchLocation);
                queryManager.UserQuery = SPPivotSettings.Query;
                queryManager.Add(locationList);
                queryManager.IsTriggered(locationList);
                XmlDocument xDoc = queryManager.GetResults(locationList);
               

                XDocument cxmlTree = new XDocument();  
                PeopleSearchResultCollection collection = new PeopleSearchResultCollection(collectionFileName);

                    using (XmlWriter cxmlWriter = cxmlTree.CreateWriter())
                    {
                        StringReader xReader = new StringReader(SPPivotSettings.Xslt);
                        XslCompiledTransform xslt = new XslCompiledTransform();
                        xslt.Load(new XPathDocument(xReader).CreateNavigator());

                        XsltArgumentList args = new XsltArgumentList();
                        
                        /* Add parameters for this transformation*/                        
                        args.AddParam("ImgBaseName", String.Empty, collection.ImageBaseName);
                        args.AddParam("DefaultImageUrl", String.Empty, SPPivotSettings.DefaultImage);

                        // Create the XmlWriter object and write some content.
                        xslt.Transform(xDoc, args, cxmlWriter);
                    }

                collection.AddItems(cxmlTree);

                return collection;

        }




        public override void EnsureSettings()
        {
                SPWeb web = SPContext.Current.Web;

              
                                   
             
                  // Load default FacetDefinitions from resources
                if (String.IsNullOrEmpty(SPPivotSettings.FacetCategories))
                {
                        using (Stream stream = typeof(SPPeopleSearch).Assembly.GetManifestResourceStream(RES_NAME_COLUMNS))
                        {
                            StreamReader reader = new StreamReader(stream);
                            SPPivotSettings.FacetCategories = reader.ReadToEnd();
                        }
                     }

                        // Load default xslt transformation settings from resources
                if (String.IsNullOrEmpty(SPPivotSettings.Xslt))
                {
                        using (Stream xslStream = typeof(SPPeopleSearch).Assembly.GetManifestResourceStream(RES_NAME_TRANSFORM))
                        {
                            StreamReader reader = new StreamReader(xslStream);
                            SPPivotSettings.Xslt = reader.ReadToEnd();
                        }
                    }

                    if (String.IsNullOrEmpty(SPPivotSettings.DefaultImage))
                    {
                        SPPivotSettings.DefaultImage = DefaultDocumentLocation;
                    }

                    if (String.IsNullOrEmpty(SPPivotSettings.Query))
                    {
                        /// use current domain name as a standard query 
                        SPPivotSettings.Query = GetCurrentUserDomain();
                    }

        }


        private static  string GetCurrentUserDomain()
        {
            try
            {
                string userLogin = SPContext.Current.Web.CurrentUser.LoginName;
                return userLogin.Substring(0,userLogin.IndexOf('\\'));
            }
            catch
            {
                return DefaultQuery;
            }
        }
    }
}
